import axios from "axios";
import {showNotify} from "vant";

const config = {
    timeout: 6 * 1000, // Timeout
    // withCredentials: true, // Check cross-site Access-Control
    // baseUrl: "/api",
};

const _axios = axios.create(config);
// _axios.defaults.baseURL = config.baseUrl;
_axios.interceptors.request.use(
    (config: any) => {
        const token = sessionStorage.getItem("token");
        if (token) {
            config.headers["Authorization"] = token;
        }
        config.headers["Content-Type"] = "application/json";
        if (config.method === "get") {
            config.params = {
                build_time: new Date().getTime(),
                ...config.params,
            };
        } //防止ie下接口数据缓存，勿要删除--fbh
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
); //请求发出拦截器

// Add a response interceptor
_axios.interceptors.response.use(
    (response) => {
        if (response.data.code !== "00000000") {
            if (
                response.data.status === 10100 ||
                response.data.status === 10103 ||
                response.data.status === 10205
            ) {
                showNotify({message: response.data.message});
                sessionStorage.clear();
                setTimeout(() => {
                    window.location.href = "";
                }, 3000);
            } else {
                showNotify({message: response.data.message});
                return Promise.reject(response.data.message);
            }
        } else {
            if (!!response.data.refreshToken) {
                sessionStorage.setItem("token", response.data.refreshToken);
            }
            return response.data.data;
        }
    },
    (error) => {
        if (!error.response) {
            showNotify({message: "服务器网络连接错误，请联系管理员并重试!"});
        } else {
            switch (error.response.status) {
                case 404:
                    //   Message.error("服务器异常!");
                    return Promise.reject();
                // break;
                case 500:
                    //   Message.error("服务器异常!");
                    return Promise.reject();
                // break;
                default:
                    //   Message.error(error.response.message);
                    return Promise.reject(error);
            }
        }
    }
); //请求接收数据拦截器
export default _axios;
